package com.zrrd.jt_admin.image.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zrrd.jt_admin.common.dto.ImageUpdateDto;
import com.zrrd.jt_admin.common.entity.Image;
import com.zrrd.jt_admin.common.response.ResponseResult;
import com.zrrd.jt_admin.common.vo.ImagePageVo;
import com.zrrd.jt_admin.file.service.FileStorageService;
import com.zrrd.jt_admin.image.service.ImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wanjl
 * @since 2024-07-03
 */
@Slf4j
@Api(tags = "图片管理")
@RestController
@RequestMapping("/admin")
@ResponseBody
public class ImageController {

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private ImageService imageService;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.bucket}")
    private String bucket;

    @ApiOperation("图片上传")
    @PostMapping("/image/upload")
    public ResponseResult upload(@RequestParam("imageClassId") Integer imageClassId,@RequestParam MultipartFile file) throws IOException {
        log.info("上传图片---》"+imageClassId);
        //上传图片
        Image image = upload(file, imageClassId);
        //把图片信息保存到数据库
        boolean flag = imageService.save(image);
        if (flag)
            return ResponseResult.defaultResponse(image, "上传成功", "上传失败");
        else
            return ResponseResult.defaultResponse(null, "上传成功", "上传失败");
    }

    private Image upload(MultipartFile file, Integer imageClassId) throws IOException {
        //上传文件
        InputStream inputStream = file.getInputStream();
        String name = file.getOriginalFilename();
        String imageFile = fileStorageService.uploadImageFile("", name, inputStream);
        //把图片信息封装成image对象
        Image image = new Image();
        image.setImageClassId(imageClassId);
        image.setUrl(endpoint + "/" + bucket + imageFile);
        image.setName(imageFile.substring(imageFile.lastIndexOf("/") + 1));
        image.setPath(imageFile);
        System.out.println(image.getName());
        System.out.println(image.getUrl());
        System.out.println(image.getPath());

        return image;
    }

    @ApiOperation(value = "修改名称", notes = "修改图片名称")
    @PutMapping("/image")
    public ResponseResult update(@RequestBody ImageUpdateDto dto) {
        boolean flag = imageService.lambdaUpdate()
                .eq(dto.getId() != null, Image::getId, dto.getId())
                .set(dto.getName() != null && !dto.equals(""), Image::getName, dto.getName())
                .update();
        return ResponseResult.updateResponse(flag);
    }


    @ApiOperation(value = "删除", notes = "删除图片")
    @DeleteMapping("/image/{id}")
    public ResponseResult remove(@PathVariable Integer id) {
        boolean flag = imageService.remove(id);
        return ResponseResult.removeResponse(flag);
    }

    @ApiOperation(value = "批量删除", notes = "批量删除图片")
    @PostMapping("/image/deleteAll")
    public ResponseResult removeAll(@RequestBody List<Integer> ids) {
        System.out.println("ids"+ids);
        boolean flag = imageService.romoveAll(ids);
        return ResponseResult.removeResponse(flag);
    }


    @ApiOperation(value = "分页查询|搜索", notes = "分页查询")
    ///adminclass/{id}/:page?limit=[:limit]&ordered=[:ordered]&keyword=[:keyword]
    @GetMapping("/imageClass/{id}/image/{page}")
    public ResponseResult findByPage(@PathVariable("id") Integer id,
                                     @PathVariable("page") Integer page,
                                     @RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit,
                                     @RequestParam(value = "ordered",required = false,defaultValue = "desc") String ordered,
                                     @RequestParam(value = "keyword",required = false,defaultValue = "") String keyword) {
        PageHelper.startPage(page, limit);
        List<Image> list = imageService.lambdaQuery()
                .eq(Image::getImageClassId, id)
                .like(!keyword.equals(""), Image::getName, keyword)
                .orderBy(ordered!=null,ordered.equals("asc")?true:false,Image::getName)
                .list();
        PageInfo<Image> pageInfo = new PageInfo<>(list);
        ImagePageVo imagePageVo=new ImagePageVo();
        imagePageVo.setList(pageInfo.getList());
        imagePageVo.setTotalCount(pageInfo.getTotal());
        return ResponseResult.queryResponse(imagePageVo);
    }


}

